from django.contrib.auth import authenticate, login
from user.models import User
from user.serializers import UserSerializer, UserTokenSerializer
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework import generics
from common.response import JsonResponse
from .token_module import get_token
from common.constant import CODE_PARAMETER_ERROR, MSG_PARAMETER_ERROR, CODE_BUSSINESS_ERROR
from user.authentication_module import TokenAuth


class Login(APIView):
    def post(self, request):
        try:
            username = request.data['username']
        except Exception:
            return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)

        # 该系统不使用密码,所有用户密码默认为123456
        password = '123456'
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            serializer = UserTokenSerializer(user)
        else:  # 不存在用户自动创建
            user = User.objects.create_user(
                username=username, password=password)
            login(request, user)
            serializer = UserTokenSerializer(user)
        serializer.set_token_data(get_token(username))
        return Response(serializer.data)


@api_view(['POST'])
def set_role(request, id):
    try:
        realName = request.data['realName']
        role = request.data['role']
    except Exception:
        return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)
    try:
        user = User.objects.get(id=id)
    except User.DoesNotExist:
        return JsonResponse(data=None, code=CODE_BUSSINESS_ERROR, message='不存在该用户')

    user.role = role
    user.realName = realName
    user.save()
    serializer = UserSerializer(user)
    return Response(serializer.data)


class DevList(mixins.ListModelMixin,
              generics.GenericAPIView):
    authentication_classes = [TokenAuth]
    queryset = User.objects.all().filter(
        role=1).filter(is_superuser=0).order_by('role')
    serializer_class = UserSerializer
    pagination_class = None

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
